<template>
  <div>
    <div class="mb15">
      <el-button @click="dialogTurnState.dialogTurnVisible = true">添加轮次</el-button>
    </div>
    <div class="group-component" v-if="groupList.length !== 0">
      <el-card v-for="(item, i) in groupList" class="mb10" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="font16">{{ item.raceRoundName }}</span>
            <el-button v-if="item.scheduleInfoList[0].raceScheduleId === undefined ||
              item.scheduleInfoList[0].raceScheduleId === null
              " type="danger" :icon="Delete" circle @click.stop="handleTurnDelete(i)" />
          </div>
        </template>
        <template #default>
          <el-collapse accordion>
            <el-collapse-item v-for="(o, index) in item.scheduleInfoList" :disabled="o.homeTeamName === '轮空' ||
              o.awayTeamName === '轮空' ||
              o.raceScheduleId === undefined ||
              o.raceScheduleId === null
              ">
              <template #title>
                <div class="card-item flex font16">
                  <div class="flex">
                    <div class="mr30">
                      {{
                        o.homeTeamName != "轮空" ? o.raceOrder : "&nbsp;&nbsp;"
                      }}
                    </div>
                    <div class="mr30">{{ o.groupName }}</div>
                  </div>
                  <el-dropdown class="card-group" trigger="hover" @command="showClick($event, o, 'homeTeamId')">
                    <div class="card-flex cursor-pointer">
                      {{ o.homeTeamName
                      }}<img :src="o.homeTeamLogo" class="card-img ml10" />
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item disabled class="drop-line">
                          <p style="color: var(--color-danger)">*</p>
                          <p>选择交换对阵位置</p>
                        </el-dropdown-item>
                        <div v-for="ot in optionList">
                          <el-dropdown-item v-if="o.homeTeamName != ot.teamName" :command="ot">
                            <p>{{ ot.teamName }}</p>
                          </el-dropdown-item>
                        </div>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <div class="ml10 mr10">vs</div>
                  <el-dropdown class="card-group-right" trigger="hover" @command="showClick($event, o, 'awayTeamId')">
                    <div class="card-flex cursor-pointer">
                      <img v-if="o.awayTeamName != '轮空'" :src="o.awayTeamLogo" class="card-img mr10" />{{ o.awayTeamName
                      }}
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item disabled class="drop-line">
                          <p style="color: var(--color-danger)">*</p>
                          <p>选择交换对阵位置</p>
                        </el-dropdown-item>
                        <div v-for="ott in optionList">
                          <el-dropdown-item v-if="o.awayTeamName != ott.teamName" :command="ott">
                            <p>{{ ott.teamName }}</p>
                          </el-dropdown-item>
                        </div>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>

                  <div class="ml30">
                    <el-button type="primary" :icon="Plus" circle @click.stop="handleAdd(item.raceRound)" />
                    <el-button v-if="o.raceScheduleId === undefined ||
                      o.raceScheduleId === null
                      " type="danger" :icon="Delete" circle @click.stop="handleDelete(item.raceRound, o, index)" />
                  </div>
                </div>
              </template>
              <el-divider border-style="dotted" />
              <el-form label-width="120px">
                <el-row justify="space-around">
                  <el-col :span="10">
                    <el-form-item label="时间">
                      <el-date-picker v-model="o.matchDate" type="datetime" placeholder="请选择"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="地点">
                      <el-input v-model="o.matchAddress" placeholder="请输入地点" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-divider border-style="dotted" />
                <el-row justify="space-around" class="mt10">
                  <el-col :span="6">
                    <el-form-item label="比赛监督">
                      <el-select v-model="o.matchSupervisionId" placeholder="请选择">
                        <el-option v-for="item in state.matchSupervisionList" :label="item.idName"
                          :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="裁判监督">
                      <el-select v-model="o.judgeSupervisionId" placeholder="请选择">
                        <el-option v-for="item in state.judgeSupervisionList" :label="item.idName"
                          :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="裁判员">
                      <el-select v-model="o.judgeId" placeholder="请选择">
                        <el-option v-for="item in state.judgeList" :label="item.idName" :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row justify="space-around" class="mt10">
                  <el-col :span="6">
                    <el-form-item label="第一助理裁判员">
                      <el-select v-model="o.firstJudgeAssistantId" placeholder="请选择">
                        <el-option v-for="item in state.firstJudgeList" :label="item.idName" :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="第二助理裁判员">
                      <el-select v-model="o.secondJudgeAssistantId" placeholder="请选择">
                        <el-option v-for="item in state.secondJudgeList" :label="item.idName"
                          :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="第四官员">
                      <el-select v-model="o.fourthOfficialId" placeholder="请选择">
                        <el-option v-for="item in state.fourOfficialList" :label="item.idName"
                          :value="item.wxUserRoleId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item class="mt20">
                  <el-button type="primary" @click="handleSubmit(o)">提交</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
            <el-row>
              <el-col :span="12" :offset="11">
                <el-button type="primary" class="mt20 mb20" @click="handleSave">保存场次</el-button>
              </el-col>
            </el-row>
          </el-collapse>
        </template>
      </el-card>
    </div>
    <el-empty v-else description="暂无数据" />
    <!-- 排位赛 - 轮次添加 -->
    <el-dialog v-model="dialogTurnState.dialogTurnVisible" title="添加轮次" width="40%">
      <el-form :model="dialogTurnState.form" ref="formTeamRef" label-width="120px">
        <el-form-item prop="turnName" label="轮次名称：">
          <el-input v-model="dialogTurnState.form.turnName" placeholder="请输入轮次名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleTurnCancel(formTeamRef)">取消</el-button>
          <el-button type="primary" @click="submitTurnForm(formTeamRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onUpdated, reactive, ref } from "vue";
import { updateRaceGroupSchedule, saveRaceGroupSchedule } from "@/api/match";
import { ElMessage, ElMessageBox } from "element-plus";
import { AttestationRoleEnum } from "../../../config/enum";
import { Plus, Delete } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

const props = defineProps([
  "raceGroupScheduleList",
  "raceTeamList",
  "raceRoleList",
  "raceGroupId",
]);
const emits = defineEmits(["getRaceGroupSchedule"]);
const optionList = ref([]);
const groupList: any = ref([]);
const allRoleList = ref([]);
const state = reactive({
  matchSupervisionList: [],
  judgeSupervisionList: [],
  judgeList: [],
  firstJudgeList: [],
  secondJudgeList: [],
  fourOfficialList: [],
});
const dialogTurnState = reactive({
  dialogTurnVisible: false,
  form: {
    turnName: "", //轮次名称
  },
});

// 排位赛 - 轮次设置
const handleTurnCancel = (formEl: FormInstance | undefined) => {
  dialogTurnState.dialogTurnVisible = false;
  if (!formEl) return;
  formEl.resetFields();
};
const submitTurnForm = (formEl: FormInstance | undefined) => {
  groupList.value.push({
    raceRound: `${Math.floor(Math.random() * 100) + 1}`,
    raceRoundName: `${dialogTurnState.form.turnName}`,
    scheduleInfoList: [
      {
        homeTeamName: "",
        awayTeamName: "",
        raceRound: "",
        raceOrder: "",
        groupName: "",
        homeTeamLogo: "",
        awayTeamLogo: "",
        matchDate: "",
        matchAddress: "",
        matchSupervisionId: "",
        judgeSupervisionId: "",
        judgeId: "",
        firstJudgeAssistantId: "",
        secondJudgeAssistantId: "",
        fourthOfficialId: "",
      },
    ],
  });
  dialogTurnState.dialogTurnVisible = false;
};

// 排位赛 - 添加场次
const handleAdd = (round: string) => {
  groupList.value.map((item: any) => {
    if (item.raceRound === round) {
      item.scheduleInfoList.push({
        homeTeamName: "",
        awayTeamName: "",
        raceRound: "",
        raceOrder: "",
        groupName: "",
        homeTeamLogo: "",
        awayTeamLogo: "",
        matchDate: "",
        matchAddress: "",
        matchSupervisionId: "",
        judgeSupervisionId: "",
        judgeId: "",
        firstJudgeAssistantId: "",
        secondJudgeAssistantId: "",
        fourthOfficialId: "",
      });
    }
  });
};
// 排位赛 - 删除轮次
const handleTurnDelete = (index: Number) => {
  ElMessageBox.confirm("是否删除该轮次？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    groupList.value.splice(index, 1);
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  });
};
// 排位赛 - 删除场次
const handleDelete = (round: string, params: any, index: Number) => {
  ElMessageBox.confirm("是否删除该场次？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (params.raceScheduleId === undefined || params.raceScheduleId === null) {
      groupList.value.map((item: any) => {
        if (item.raceRound === round) {
          item.scheduleInfoList.splice(index, 1);
        }
      });
    }
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  });
};
const handleSave = async () => {
  let isOut = false;
  groupList.value.map((item: any) => {
    item.scheduleInfoList.map((it: any) => {
      if (it.awayTeamName === "") {
        isOut = true;
      }
    });
  });
  if (isOut) {
    return ElMessage.warning("请选择对阵球队！");
  }
  const res = await saveRaceGroupSchedule({
    raceStageId: props.raceGroupId,
    scheduleList: groupList.value,
  });
  if (res.code === 200) {
    ElMessage.success(res.msg);
    emits("getRaceGroupSchedule");
  } else {
    ElMessage.warning(res.msg);
  }
};
// 团队点击
const showClick = (e: any, item: any, value: string) => {
  if (value === "homeTeamId") {
    item.homeTeamId = e.teamId;
    item.homeTeamName = e.teamName;
  } else if (value === "awayTeamId") {
    item.awayTeamId = e.teamId;
    item.awayTeamName = e.teamName;
  }
  if (item.raceScheduleId != undefined || item.raceScheduleId != null) {
    handleSubmit(item);
  }
};

// 提交数据
const handleSubmit = async (item: any) => {
  const res = await updateRaceGroupSchedule(item);
  if (res.code === 200) {
    ElMessage.success(res.msg);
    emits("getRaceGroupSchedule");
  } else {
    ElMessage.warning(res.msg);
  }
};

const updateRoleList = () => {
  allRoleList.value.map((item: any) => {
    switch (item.roleType) {
      case AttestationRoleEnum.MATCH_SUPERVISION: // 比赛监督
        state.matchSupervisionList = item.wxUserRoleList;
        break;
      case AttestationRoleEnum.JUDGE_SUPERVISION: // 裁判监督
        state.judgeSupervisionList = item.wxUserRoleList;
        break;
      case AttestationRoleEnum.JUDGE: // 裁判员
        state.judgeList = item.wxUserRoleList;
        break;
      case AttestationRoleEnum.FIRST_JUDGE_ASSISTEANT: // 第一裁判助理
        state.firstJudgeList = item.wxUserRoleList;
        break;
      case AttestationRoleEnum.SECOND_JUDGE_ASSISTEANT: // 第二裁判助理
        state.secondJudgeList = item.wxUserRoleList;
        break;
      case AttestationRoleEnum.FOURTH_OFFICIAL: // 第四官员
        state.fourOfficialList = item.wxUserRoleList;
    }
  });
};
// 数据初始
onUpdated(() => {
  groupList.value = props.raceGroupScheduleList;
  optionList.value = props.raceTeamList;
  allRoleList.value = props.raceRoleList;
  updateRoleList();
});
</script>

<style  lang="scss" scoped>
.group-component {
  ::v-deep {
    .el-collapse-item__header {
      height: auto;
    }

    .el-collapse {
      border-top: 0px;
    }

    .el-card__body {
      padding: 0px;
    }
  }

  .card-flex,
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-item {
    align-items: center;
    padding: 15px 20px;
    width: 100%;
  }

  .card-group {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    min-width: 0;
  }

  .card-group-right {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    min-width: 0;
  }

  .card-img {
    width: 47px;
    height: 47px;
  }

  .drop-line {
    text-decoration: underline;
  }
}
</style>
